import React from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { Spin } from 'antd'
import { useQuery } from 'react-query'
import { authApi, authUtils } from '../services/auth'

interface ProtectedRouteProps {
  children: React.ReactNode
  requiredRole?: string
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ 
  children, 
  requiredRole 
}) => {
  const location = useLocation()
  
  // 检查是否有token
  const isAuthenticated = authUtils.isAuthenticated()
  
  // 验证token有效性
  const { data: currentUser, isLoading, error } = useQuery(
    'currentUser',
    authApi.getCurrentUser,
    {
      enabled: isAuthenticated,
      retry: false,
      onSuccess: (data) => {
        authUtils.saveUser(data)
      },
      onError: () => {
        // Token无效，清除本地存储
        authUtils.logout()
      },
    }
  )

  // 如果没有token，重定向到登录页
  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />
  }

  // 正在验证token
  if (isLoading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
      }}>
        <Spin size="large" tip="验证登录状态..." />
      </div>
    )
  }

  // Token验证失败
  if (error) {
    return <Navigate to="/login" state={{ from: location }} replace />
  }

  // 检查角色权限
  if (requiredRole && currentUser) {
    const hasPermission = authUtils.hasRole(requiredRole)
    if (!hasPermission) {
      return (
        <div style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100vh',
          flexDirection: 'column',
        }}>
          <h2>访问被拒绝</h2>
          <p>您没有访问此页面的权限</p>
        </div>
      )
    }
  }

  return <>{children}</>
}

export default ProtectedRoute